package com.inkyi.assistant.app.tools.comps;

import com.inkyi.assistant.app.tools.base.InkTools;
import com.inkyi.framework.common.lang.CmdStreamRunnable;
import com.inkyi.framework.common.utils.NetUtil;
import com.inkyi.framework.common.utils.RuntimeHelper;
import com.inkyi.framework.common.utils.SystemHelper;
import com.inkyi.framework.daqian.share.layout.HorizontalLayout;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.LinkedHashSet;
import java.util.Objects;

public class NetworkTool extends JPanel implements InkTools {


    private JPanel headerPanel;

    private JTextArea textArea;

    private JScrollPane scrollPane;

    private JButton ipButton;

    private JButton natButton;

    private JButton localIp4Button;

    private JButton localIp6Button;

    private JButton publicIp4Button;

    private JButton pingButton;

    private JButton telnetButton;

    private Thread streamComThread;

    public NetworkTool() {
        initComponents();
    }


    @Override
    public void initComponents() {
        setLayout(new BorderLayout());
        ipButton = new JButton("ipconfig");
        natButton = new JButton("netstat -nat");
        localIp4Button = new JButton("本机IP4");
        localIp6Button = new JButton("本机IP6");
        publicIp4Button = new JButton("公网IP4");
        pingButton = new JButton("PING");
        telnetButton = new JButton("Telnet");

        headerPanel = new JPanel();
        headerPanel.setLayout(new HorizontalLayout(2));
        headerPanel.add(ipButton);
        headerPanel.add(natButton);
        headerPanel.add(localIp4Button);
        headerPanel.add(localIp6Button);
        headerPanel.add(publicIp4Button);
        headerPanel.add(pingButton);
        headerPanel.add(telnetButton);

        textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setBackground(Color.black);
        textArea.setForeground(Color.green);

        scrollPane = new JScrollPane(textArea);

        this.add(headerPanel, BorderLayout.NORTH);
        this.add(scrollPane, BorderLayout.CENTER);
        ipButton.addActionListener(e -> {
            try {
                String ipConfigStr;
                if (SystemHelper.isWindowsOS()) {
                    ipConfigStr = RuntimeHelper.execForStr("ipconfig");
                } else {
                    ipConfigStr = RuntimeHelper.execForStr("ifconfig");
                }
                textArea.setText(ipConfigStr);
                textArea.setCaretPosition(0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        natButton.addActionListener(e -> {
            try {
                String ipConfigStr;
                if (SystemHelper.isWindowsOS()) {
                    ipConfigStr = RuntimeHelper.execForStr("ipconfig /all");
                } else {
                    ipConfigStr = RuntimeHelper.execForStr("netstat -nat");
                }
                textArea.setText(ipConfigStr);
                textArea.setCaretPosition(0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        localIp4Button.addActionListener(e -> {
            try {
                LinkedHashSet<InetAddress> inetAddresses = NetUtil.localAddressList(address -> address instanceof Inet4Address);
                StringBuilder sb = new StringBuilder();
                for (InetAddress inetAddress : inetAddresses) {
                    sb.append(inetAddress.getHostAddress());
                    sb.append("\n");
                }
                textArea.setText(sb.toString());
                textArea.setCaretPosition(0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        localIp6Button.addActionListener(e -> {
            try {
                LinkedHashSet<InetAddress> inetAddresses = NetUtil.localAddressList(address -> address instanceof Inet6Address);
                StringBuilder sb = new StringBuilder();
                for (InetAddress inetAddress : inetAddresses) {
                    sb.append(inetAddress.getHostAddress());
                    sb.append("\n");
                }
                textArea.setText(sb.toString());
                textArea.setCaretPosition(0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        publicIp4Button.addActionListener(e -> {
            try {
                StringBuilder sb = new StringBuilder();
                String queryURL = JOptionPane.showInputDialog("查询服务器", "https://icanhazip.com/");
                if (queryURL != null && !queryURL.isEmpty()) {
                    URL url = new URI(queryURL).toURL();
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    try (InputStream inputStream = connection.getInputStream();
                         InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                         BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                        String line;
                        while ((line = bufferedReader.readLine()) != null) {
                            sb.append(line);
                            sb.append("\n");
                        }
                    } finally {
                        connection.disconnect();
                    }
                }
                textArea.setText(sb.toString());
                textArea.setCaretPosition(0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        pingButton.addActionListener(e -> {
            JButton source = (JButton) e.getSource();
            String buttonText = source.getText();

            if (Objects.equals("PING", buttonText)) {
                String queryURL = JOptionPane.showInputDialog("输入要Ping的地址", "");
                if (queryURL == null || queryURL.isEmpty()) {
                    textArea.setText("地址不正确");
                    textArea.setCaretPosition(0);
                    return;
                }
                if (streamComThread == null || !streamComThread.isAlive()) {
                    // 清空区域
                    textArea.setText("");
                    textArea.setCaretPosition(0);
                    streamComThread = Thread.startVirtualThread(new CmdStreamRunnable(new String[]{"ping " + queryURL}, new CmdStreamRunnable.Callback() {
                        @Override
                        public void content(String line) {
                            if (line != null) {
                                textArea.append(line + "\n");
                            }
                        }
                    }));
                }
                source.setText("取消PING");
            }
            if (Objects.equals("取消PING", buttonText)) {
                try {
                    streamComThread.interrupt();
                    streamComThread.join(1000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                } finally {
                    textArea.setText("");
                    textArea.setCaretPosition(0);
                    source.setText("PING");
                }
            }
        });
        telnetButton.addActionListener(e -> {
            String inputString = JOptionPane.showInputDialog("输入主机的IP或者域名+空格+端口号", "");
            String[] split = inputString.split(" ");
            String hostname = split[0];
            String port = split[1];
            int timeout = 200;

            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(hostname, Integer.parseInt(port)), timeout);
                boolean isConnected = socket.isConnected();
                textArea.setText("telnet " + hostname + " " + port + "\n==>isConnected: " + isConnected);
                textArea.setCaretPosition(0);
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        });
    }

    @Override
    public String getToolCode() {
        return "network-ip";
    }

    @Override
    public String getToolName() {
        return "网络信息";
    }

    @Override
    public String getToolID() {
        return "tools-" + getToolCode();
    }
    @Override
    public String getOpenType() {
        return "workspace";
    }

    @Override
    public Container getComponent() {
        return this;
    }

    public static void main(String[] args) {

    }


}
